package com.zjl.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zjl.dto.DishDto;
import com.zjl.pojo.*;
import com.zjl.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private SetMealDishService setMealDishService;

    @Autowired
    private SetMealService setMealService;

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    /**
     * 菜品信息分页
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public Result<Page<DishDto>> select(int page, int pageSize, String name) {
        log.info("分页查询： page = {}, pageSize = {}", page, pageSize);
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>();
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(name != null, Dish::getName, name);
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        dishService.page(pageInfo, queryWrapper);

        BeanUtils.copyProperties(pageInfo, dishDtoPage, "records");
        List<Dish> records = pageInfo.getRecords();
        List<DishDto> list = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if(category != null) {
                dishDto.setCategoryName(category.getName());
            }
            return dishDto;
        }).collect(Collectors.toList());
        dishDtoPage.setRecords(list);
        return Result.success(dishDtoPage);
    }

    /**
     * 新增菜品
     * @param dishDto
     * @return
     */
    @PostMapping
    public Result<String> save(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());
        dishService.saveWithFlavor(dishDto);

        // 清理所有菜品的缓存数据
        /*Set<Object> keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);*/

        // 清楚某个分类下面的菜品缓存数据
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);

        return Result.success("新增菜品成功！");
    }

    /**
     * 根据id查询菜品信息和对应的口味信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result<DishDto> get(@PathVariable Long id) {
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return Result.success(dishDto);
    }

    /**
     * 修改菜品
     * @param dishDto
     * @return
     */
    @PutMapping
    public Result<String> update(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());
        dishService.updateWithFlavor(dishDto);

        // 清理所有菜品的缓存数据
        /*Set<Object> keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);*/

        // 清楚某个分类下面的菜品缓存数据
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);

        return Result.success("修改菜品成功！");
    }

    /**
     * 修改菜品的售卖状态
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("status/{status}")
    public Result<String> updateStatus(@PathVariable("status") Integer status, @RequestParam List<Long> ids) {
        log.info("修改菜品的售卖状态: status: {}, ids:{}",status, ids.toString());
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(ids != null, Dish::getId, ids);
        List<Dish> list = dishService.list(queryWrapper);

        for(Dish dish : list) {
            if(dish != null) {
                dish.setStatus(status);
                dishService.updateById(dish);
            }
        }
        return Result.success("售卖状态修改成功！");
    }

    /**
     * 菜品批量删除
     * @param ids
     * @return
     */
    @DeleteMapping
    public Result<String> delete(@RequestParam("ids") List<Long> ids) {
        // 查询那些套餐包含该菜品
        LambdaQueryWrapper<SetMealDish> setMealDishQueryWrapper = new LambdaQueryWrapper<>();
        setMealDishQueryWrapper.in(ids != null, SetMealDish::getDishId, ids);
        List<SetMealDish> setMealDishList = setMealDishService.list(setMealDishQueryWrapper);

        // 套餐里均没有该菜品，可以删除
        if(setMealDishList.size() == 0) {
            // 逻辑删除菜品
            dishService.deleteByIds(ids);
            // 逻辑删除菜品对应的口味
            LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(DishFlavor::getDishId, ids);
            dishFlavorService.remove(queryWrapper);
            return Result.success("菜品删除成功！");
        }

        // set_meal_id
        ArrayList<Long> setMealIDList = setMealDishList.stream().map(item -> {
            return item.getSetMealId();
        }).collect(Collectors.toCollection(ArrayList::new));
        LambdaQueryWrapper<SetMeal> SetMealQueryWrapper = new LambdaQueryWrapper<>();
        SetMealQueryWrapper.in(SetMeal::getId, setMealIDList);
        List<SetMeal> setMealList = setMealService.list(SetMealQueryWrapper);

        // 判断有该菜品的套餐 售卖中X 停售中_/
        for(SetMeal setMeal : setMealList) {
            Integer status = setMeal.getStatus();
            // 有套餐正在出售 不能删除
            if(status == 1) {
                return Result.error("该菜品有关联的在售套餐，删除失败！");
            }
        }
        // 所有有该菜品的套餐均在停售中 删除
        dishService.deleteByIds(ids);
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(DishFlavor::getDishId, ids);
        dishFlavorService.remove(queryWrapper);
        return Result.success("菜品删除成功！");
    }

    /**
     * 根据CategoryId查询在售菜品
     * @param categoryId
     * @return
     */
    /*@GetMapping("list")
    public Result<List<Dish>> getByCategoryId(@RequestParam("categoryId") Long categoryId) {
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dish::getCategoryId, categoryId);
        queryWrapper.eq(Dish::getStatus, 1);
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> dishList = dishService.list(queryWrapper);
        return Result.success(dishList);
    }*/

    /**
     * 查询list（categoryId）
     * @param dish
     * @return
     */
    @GetMapping("list")
    public Result<List<DishDto>> list(Dish dish) {
        List<DishDto> dishDtoList = null;

        // 动态构建key
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();

        // 先从redis中获取缓存数据
        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);

        if(dishDtoList != null) {
            return Result.success(dishDtoList);
        }

        // 构建查询条件,根据categoryId查询status为1的菜品列表
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        queryWrapper.eq(Dish::getStatus, 1);
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> dishList = dishService.list(queryWrapper);

        // 将查询到的值复制到DishDto
        dishDtoList = dishList.stream().map(item -> {
            // 创建DishDto对象
            DishDto dishDto = new DishDto();
            // 将已有的属性先复制到DishDto对象里面
            BeanUtils.copyProperties(item, dishDto);
            // 获取分类名称
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if(category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            // 获取菜品对应的口味
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(DishFlavor::getDishId, dishId);
            List<DishFlavor> dishFlavorList = dishFlavorService.list(queryWrapper1);
            dishDto.setFlavors(dishFlavorList);
            return dishDto;
        }).collect(Collectors.toList());
        // 如果不存在，查询数据库并插入到Redis中
        redisTemplate.opsForValue().set(key, dishDtoList, 60, TimeUnit.MINUTES);

        return Result.success(dishDtoList);
    }
}
